package com.maiyawx.mall.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.maiyawx.mall.exception.WxException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * 微信请求类
 */
public class WxHttpsUtil {

    /**
     * get请求
     * @param url
     * @return
     */
    public static JSONObject get(String url)
    {
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        JSONObject data = JSON.parseObject(response);
        if (data.get("errcode") != null) {
            throw new WxException(data);
        }
        return data;
    }

    /**
     * post请求
     * @param url
     * @param requestJson
     * @return
     */
    public static JSONObject post(String url,JSONObject requestJson)
    {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(requestJson),headers);
        String response = restTemplate.postForObject(url, entity, String.class);
        JSONObject data = JSON.parseObject(response);
        return data;
    }
}
